from django.shortcuts import render

# Create your views here.
from django.shortcuts import render
from django.http import HttpResponse
from django_redis import get_redis_connection
from .models import Post
from new01 import models


from openai import OpenAI

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
import httpx
import os
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import base64
import requests
import json
from django.conf import settings
from django.shortcuts import render, redirect
from django.http import JsonResponse
import ssl

from .forms import ImageUploadForm
from .models import ImageUpload
from django.http import StreamingHttpResponse
def index(request):

    # 获取Redis连接
    redis_client = get_redis_connection('default')
    redis_client.set('my_value', "my_value")
    value = redis_client.get('my_value')
    print('value ====>' + str(value))

    # model = ChatOpenAI(
    #     model_name="deepseek-chat",
    #     openai_api_key="sk-6fa5b8cec19c452bab9abf3133988a8e",
    #     openai_api_base="https://api.deepseek.com/v1"
    # )
    #
    # image_url = "http://du1888.top/img123.jpg"
    # image_data = base64.b64encode(httpx.get(image_url).read()).decode("utf-8")
    # message = HumanMessage(
    #     content=json.dumps([
    #         {"type": "text", "text": "这张图片里面有什么？"},
    #         {"type": "image", "image": {"data": image_data, "format": "base64"}},
    #     ])
    # )
    #
    # response = model.invoke([message])
    # print("------------------------- start ---")
    # print(response.content)
    # print("------------------------- end ---")

    # 填写你的 API Key
    API_KEY = "sk-6fa5b8cec19c452bab9abf3133988a8e"

    url = "https://api.deepseek.com/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}"
    }

    data = {
        "model": "deepseek-chat",  # 指定使用 R1 模型（deepseek-reasoner）或者 V3 模型（deepseek-chat）
        "messages": [
            {"role": "system", "content": "你是一个专业的助手"},
            {"role": "user", "content": "你是谁？"}
        ],
        "stream": False  # 关闭流式传输
    }

    data["stream"] = True

    response = requests.post(url, headers=headers, json=data, stream=True)

    for line in response.iter_lines():
        if line:
            decoded_line = line.decode('utf-8')
            print(" 11==> " + decoded_line)


    return HttpResponse("Hello, world. You're at the polls index.11")

def index2(request):
    # 下载并编码图片
    image_url = "https://www.du1888.top/img123.jpg"
    # image_url = "https://wx4.sinaimg.cn/mw690/007jCdDZgy1h84021iessj30u00tj0ul.jpg"
    image_data = base64.b64encode(httpx.get(image_url).read()).decode("utf-8")

    # 配置DeepSeek模型
    model = ChatOpenAI(
        model_name="deepseek-chat",
        openai_api_key="sk-6fa5b8cec19c452bab9abf3133988a8e",
        openai_api_base="https://api.deepseek.com/v1"
    )

    # 构建多模态消息
    message = HumanMessage(
        content=json.dumps([
            {"type": "text", "text": "该图,在建筑工地上有哪些不规范的地方"},
            {
                "type": "image",
                "source_type": "url",
                "url": image_url,
            },

        ])
    )

    # 调用API
    # response = model.invoke([message])
    # print(response.content)
    # stream 流式
    response = StreamingHttpResponse(model.stream([message]))

    response["Cache-Control"] = "no-cache"
    response["X-Accel-Buffering"] = "no"
    response["Content-Type"] = "text/event-stream; charset=utf-8"

    # 添加 CORS 头
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, OPTIONS"
    response["Access-Control-Allow-Headers"] = "Content-Type"
    return response

    # return HttpResponse("Hello, world. You're at the polls index.22")

def web01(request):
    return render(request, "web01.html")

def show_name(request):
    context = {'name_list': Post.objects.all()}
    return render(request, "web01.html", context)

def student_list(request):
    student_queryset = models.New01Student.objects.all()
    context = {'student_queryset': student_queryset}
    print('==================:' + str(student_queryset.values()))
    return render(request, "web02.html",context)


def get_ai_response(messages):

    client = OpenAI(api_key="sk-6fa5b8cec19c452bab9abf3133988a8e", base_url="https://api.deepseek.com")
    try:
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            stream=False
        )
        print('ai==>>>' + response.choices[0].message.content)

        return  {
            'content': response.choices[0].message.content,
            'reasoning': getattr(response.choices[0], 'reasoning_content','')
        }
    except Exception as e:
        return {
            'content': f'处理错误: {str(e)}',
            'reasoning': ''
        }

def chat_view(request):

    if 'messages' not in request.session:
        request.session['messages'] = []
    if request.method == 'POST':
        user_message = request.POST.get('message', '')
        if user_message:
            request.session['messages'].append({'role': 'user', 'content': user_message})

            response = get_ai_response(request.session['messages'])

            request.session['messages'].append({
                'role': 'assistant',
                'content': response['content'],
                'reasoning': response['reasoning']
            })
            request.session.modified = True
    print({
        'messages': request.session['messages'],
    })
    return render(request, 'chat.html', {
        'messages': request.session['messages'],
    })
    # messages = [
    #     {"role": "system", "content": "You are a helpful assistant"},
    #     {"role": "user", "content": "你好,你是谁，说一下今天是星期几"},
    # ]
    # get_ai_response(messages)
    # return HttpResponse("Hello, AI")


def upload_image(request):
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            image_upload = form.save()
            return redirect('process_image', image_id=image_upload.id)
    else:
        form = ImageUploadForm()
    return render(request, 'upload.html', {'form': form})


def process_image(request, image_id):
    try:
        image_upload = ImageUpload.objects.get(id=image_id)

        # 将图像转换为base64
        with open(image_upload.image.path, "rb") as image_file:
            base64_image = base64.b64encode(image_file.read()).decode('utf-8')

        # 准备API请求
        headers = {
            "Authorization": f"Bearer {settings.DEEPSEEK_API_KEY}",
            "Content-Type": "application/json"
        }

        payload = {
            "model": "deepseek-chat",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "请详细描述这张图片的内容。"},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:image/jpeg;base64,{base64_image}"
                            }
                        }
                    ]
                }
            ],
            "max_tokens": 1000
        }

        # 调用DeepSeek API
        response = requests.post(settings.DEEPSEEK_API_URL, headers=headers, json=payload)

        if response.status_code == 200:
            result = response.json()
            description = result['choices'][0]['message']['content']

            # 保存描述到数据库
            image_upload.description = description
            image_upload.save()

            return render(request, 'results.html', {
                'image': image_upload,
                'description': description
            })
        else:
            error_message = f"API请求失败: {response.status_code} - {response.text}"
            return render(request, 'results.html', {
                'error': error_message,
                'image': image_upload
            })

    except ImageUpload.DoesNotExist:
        return render(request, 'results.html', {'error': '图片不存在'})
    except Exception as e:
        return render(request, 'results.html', {'error': f'处理错误: {str(e)}'})


def home(request):
    return render(request, 'home.html')